import type { BwPriceAskParams, BwPriceAskWords } from '@/services/price-sheet/getBwPriceAskWords'
import type { PriceData } from '@/views/price-sheet/hooks/usePriceTable'
import { ChannelTypeEnum, CreativePictureEnum, TypeEnum, VersionTypeEnum } from '@/core/enums/type'
import { number, z } from 'zod'
import { PlatformToClientType } from '@/core/mapper/platform'
import { compact, isNaN, isNil } from 'lodash-es'
import { PlatformEnum, PricePlatform, ProductEnum } from '@/core/enums/platform'
import { useMainStore } from '@/store/useMainStore'
import { message } from 'ant-design-vue'
import { BwComboPriceNameKeyMap } from '@/views/price-sheet/interface'
import { ComboPriceNameEnum, OnLinePeriodEnum } from '@/core/enums/name'
import { ApproveStatusEnum } from '@/core/enums/status'

export function bwPriceDataNormalizer(
  BwFormFields: BwPriceAskParams,
  bwPriceInfo: BwPriceAskWords,
  currentBaiduPriceData: Partial<PriceData>,
  current360PriceData: Partial<PriceData>,
  hasCreativePicture: CreativePictureEnum,
  comboName: string,
  versionType: VersionTypeEnum,
  qihu360Select: boolean,
  totalPrice: string,
  pcSold: boolean,
  mobileSold: boolean,
  premiumRatio: number,
  proTotalPrice: string,
  type: ProductEnum
): z.infer<ReturnType<typeof bwPriceDataParser>> | boolean {
  function wordWith360AndClientType() {
    const clientType = PlatformToClientType[current360PriceData.columnName!]
    const wordAskWords = bwPriceInfo.wordAskWords.map((word) => {
      return {
        ...word,
        channelType: ChannelTypeEnum.QiHu360
      }
    })

    if (isNil(clientType)) {
      return wordAskWords
    }

    if (clientType === PlatformEnum.Platform) {
      return wordAskWords
    } else {
      return wordAskWords.filter((word) => word.clientType === clientType)
    }
  }

  function wordWithBaiduAndClientType() {
    const clientType = PlatformToClientType[currentBaiduPriceData.columnName!]
    const wordAskWords = bwPriceInfo.wordAskWords.map((word) => {
      return {
        ...word,
        channelType: ChannelTypeEnum.Baidu
      }
    })

    if (isNil(clientType)) {
      return wordAskWords
    }

    if (clientType === PlatformEnum.Platform) {
      return wordAskWords
    } else {
      return wordAskWords.filter((word) => word.clientType === clientType)
    }
  }

  const mainStore = useMainStore()

  const priceAskWords: ReturnType<typeof wordWithBaiduAndClientType> = wordWithBaiduAndClientType()
  const priceAskWords360: ReturnType<typeof wordWith360AndClientType> = qihu360Select ? wordWith360AndClientType() : []

  if (pcSold && currentBaiduPriceData.columnName === PricePlatform.PC) {
    message.error('pc端关键词已出售')
    return false
  }

  if (mobileSold && currentBaiduPriceData.columnName === PricePlatform.Mobile) {
    message.error('移动端关键词已出售')
    return false
  }

  if (!qihu360Select) {
    if (pcSold && mobileSold) {
      message.error('关键词已售出')
      return false
    }

    // 百度标王和360标王都没选
    if (!currentBaiduPriceData.dataIndex) {
      message.error('请选择报价内容')
      return false
    }

    // 边界问题，考虑到关键词筛选后为空的情况，则提示他选择报价内容
    if (priceAskWords.length === 0) {
      message.error('关键词提交失败，请重新查价')
      return false
    }
  }

  return {
    proxyId: mainStore.userInfo?.proxy_id,
    proxyName: mainStore.userInfo?.proxy_name,
    sellerId: mainStore.userInfo?.id,
    sellerName: mainStore.userInfo?.full_name,
    productId: type,
    userArea: BwFormFields.userAreas[0],
    priceAskWords,
    priceAskWords360,
    assessmentPricesId: BwFormFields.assessmentPricesId,
    areas: BwFormFields.serviceAreas.join(','),
    onLinePeriod: currentBaiduPriceData.onLinePeriod ?? '',
    comboName,
    comboPriceName: BwComboPriceNameKeyMap[currentBaiduPriceData.timer!],
    assessmentPrice: isNaN(Number(totalPrice)) ? undefined : Number(totalPrice),
    industryCode: bwPriceInfo.subjectCode,
    clientType: PlatformToClientType[currentBaiduPriceData.columnName!],
    hasCreatePic: hasCreativePicture,
    versionType: versionType,
    type: TypeEnum.NEW,
    premiumRatio,
    marketPrice: isNaN(Number(proTotalPrice)) ? undefined : Number(proTotalPrice),
    approveStatus: bwPriceInfo.approveStatus,
    channelPrices: compact([
      {
        channelType: ChannelTypeEnum.Baidu,
        basePriceTypeId: currentBaiduPriceData.priceTypeId,
        hasCreativePicture: hasCreativePicture,
        versionType: versionType
      },
      qihu360Select && {
        channelType: ChannelTypeEnum.QiHu360,
        basePriceTypeId: current360PriceData.priceTypeId,
        columnName: current360PriceData.columnName,
        quote: current360PriceData.quote,
        comboPriceName: BwComboPriceNameKeyMap[current360PriceData.timer!]
      }
    ])
  }
}

export function bwPriceDataParser() {
  return z.object({
    costRate: z.number().optional().nullable(),

    machineExamine: z.number().optional().nullable(),

    proxyId: z.number().optional().nullable(),
    proxyName: z.string().optional().nullable(),
    sellerId: z.number().optional().nullable(),
    sellerName: z.string().optional().nullable(),
    productId: z.nativeEnum(ProductEnum),
    userArea: z.string(),
    premiumRatio: z.number(),
    marketPrice: z.number().optional(),
    priceAskWords: z.any().array(),
    priceAskWords360: z.any().array(),
    assessmentPricesId: z.number(),
    areas: z.string(),
    onLinePeriod: z.nativeEnum(OnLinePeriodEnum).or(z.string()),
    comboName: z.string(),
    comboPriceName: z.nativeEnum(ComboPriceNameEnum),
    assessmentPrice: z.number().optional(),
    industryCode: z.number().optional(),
    clientType: z.nativeEnum(PlatformEnum),
    hasCreatePic: z.nativeEnum(CreativePictureEnum),
    versionType: z.nativeEnum(VersionTypeEnum),
    type: z.nativeEnum(TypeEnum),
    approveStatus: z.nativeEnum(ApproveStatusEnum),
    oldOrderId: z.number().optional().nullable(),
    channelPrices: z.array(
      z.union([
        z.object({
          channelType: z.nativeEnum(ChannelTypeEnum),
          basePriceTypeId: z.number().optional(),
          hasCreativePicture: z.nativeEnum(CreativePictureEnum),
          versionType: z.nativeEnum(VersionTypeEnum)
        }),
        z.object({
          channelType: z.nativeEnum(ChannelTypeEnum),
          basePriceTypeId: z.number().optional(),
          columnName: z.nativeEnum(PricePlatform).optional().optional(),
          quote: z.string().optional(),
          comboPriceName: z.nativeEnum(ComboPriceNameEnum).optional()
        })
      ])
    )
  })
}
